﻿/*
创建日期:	2019/5/11 23:54:20     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)    ZhCun.cn
描	述：
记	录：
*/
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using ZhCun.DbCore.Entitys;

namespace ZhCun.DbCore.Cores
{
    public interface IQueryCondition : ICondition
    {
        Dictionary<Expression, EmQueryOrder> OrderExpressions { get; }
        int PageNo { set; get; }
        int PageSize { set; get; }
        int Total { get; }
        int TotalPage { get; }
    }

    /// <summary>
    /// 用于框架的查询条件对象，包含where条件与排序
    /// </summary>
    /// <typeparam name="TEntity">框架实体类型</typeparam>
    public class QueryCondition<TEntity> : ExecCondition<TEntity>, IQueryCondition where TEntity : EntityBase, new()
    {
        public QueryCondition()
        {
            OrderExpressions = new Dictionary<Expression, EmQueryOrder>();
        }
        /// <summary>
        /// 排序表达式集合
        /// </summary>
        public Dictionary<Expression, EmQueryOrder> OrderExpressions { get; private set; }
        /// <summary>
        /// 页码
        /// </summary>
        public int PageNo { set; get; }
        /// <summary>
        /// 每页记录数
        /// </summary>
        public int PageSize { set; get; }
        /// <summary>
        /// 用来输出分页时的记录总数
        /// </summary>
        public int Total { protected internal set; get; }
        /// <summary>
        /// 用来输出的分页时的页总数
        /// </summary>
        public int TotalPage
        {
            get
            {
                if (PageNo > 0 && PageSize > 0)
                {
                    int pageCount = Total / PageSize;
                    if (Total % PageSize != 0)
                    {
                        pageCount++;
                    }
                    return pageCount;
                }
                return 0;
            }
        }

        public new QueryCondition<TEntity> WhereAnd(Expression<Func<TEntity, bool>> whereExpress)
        {
            base.WhereAnd(whereExpress);
            return this;
        }

        public new QueryCondition<TEntity> WhereOr(Expression<Func<TEntity, bool>> whereExpress)
        {
            base.WhereOr(whereExpress);
            return this;
        }

        /// <summary>
        /// 指定排序类型对指定字段进行排序
        /// </summary>
        public QueryCondition<TEntity> OrderBy(Expression<Func<TEntity, object>> selector, EmQueryOrder orderType)
        {
            OrderExpressions.Add(selector, orderType);
            return this;
        }
        /// <summary>
        /// 以升序方式对指定字段进行排序
        /// </summary>
        public QueryCondition<TEntity> OrderBy(Expression<Func<TEntity, object>> selector)
        {
            OrderBy(selector, EmQueryOrder.Asc);
            return this;
        }
    }
}